<?php

    class News_Controller extends Application {
        
        function setup()
        {
            $this->actions = array('index','modify','delete','categories','delete_category',
                                   'modify_category','search','browse_month','add_category','modify');
            $this->use_layout('admin_layout.php');
            $this->before_filter('is_logged_in');
            $this->before_filter('has_access');
            use_model('news','news_categories');

			// subnav
			$subnav = array();
			$subnav['View All News'] = array('controller'=>'admin/news' );
			$subnav['Add News'] = array('controller'=>'admin/news' ,'action'=>'modify');
			if(has_access_to('News::Manage News Categories')) 
			{
				$subnav['Manage Categories'] = array('controller'=>'admin/news' ,'action'=>'categories');				
			}
			if (has_access_to('News::Manage Comments')) {
			    $subnav['Manage Comments'] = array('controller'=>'admin/comments');
			}
			$this->assign('subnav',$subnav);
        }

        function has_access()
        {
            if (!has_access_to('News::Access News')) $this->redirect_to(array('controller'=>'admin/dashboard' ));
        }
        
		function index() 
		{
		    // list all news articles
		    $news = new News();		    
	        $this->assign('report',$news->get_paged_news());
	        $draft_list = $news->find_rows(array(
	                                    'conditions'=>'status=0',
	                                    'fields'=>array('id','title')
	                                 ));
	        $this->assign('draft_list',$draft_list);
		}

		function browse_month()
		{
		    if ( !empty($_POST['date']['year']) 
		         && !empty($_POST['date']['mon']) )
		    {
		        $news = new News();
		        $this->assign('report',$news->browse_by_month( $_POST['date']['mon'],$_POST['date']['year'] ) );
		        $mdate  = get_month((int) $_POST['date']['mon']);
		        $ydate  = (int) $_POST['date']['year'];
		        $this->assign('search_date', "$mdate $ydate");
		    } else {
		        $this->redirect_to('index');
		    }
		}
        
        function modify()
        {            
            if ( !has_access_to('News::Add News') || !has_access_to('News::Edit News') )
            {
                $this->redirect_to('index');
            }
            
            $news = new News();
		    $this->assign_ref('news',$news);
		    
		    $news_categories = new News_Categories();		    
		    $this->assign_ref('news_categories', $news_categories);
		    
		    // if editing from front of site, this will allow user to return to that post upon save
		    $go_back_to = isset($_GET['from_edit']) ? htmlspecialchars($_SERVER['HTTP_REFERER']) : '';
		    $this->assign('go_back_to', $go_back_to);
		    

		    // load via id parameter
		    if ( $this->is_get() && isset($_GET['id']) )
		    {
		        if ( $news->load( (int) $_GET['id'] ) )
		        {
		            $this->assign('news_item_categories', $news->selected_categories());
		        }
		    }
		    
		    // save post
		    if ( $this->is_post() )
		    {  
    		    if (!$news->load( (int) $_POST['news']['id'])) {
    		        flash('error','News entry failed to load for saving');
    		        $this->redirect_to('index');
    		    }
		        
		        // change timestamp?
		        if ( isset($_POST['edit_timestamp']) )
		        {
		            $_POST['news']['publish_date'] = $_POST['date'];
		        }
		        
		        if ( isset($_POST['commit']) && $_POST['commit'] == 'Publish')
		        {
		            $_POST['news']['status'] = 1; // publish it
		        }
		        
		        if ( $news->update_fields($_POST['news']))
	            {		            
	                flash('notice','Post Saved');	                
	                // ajax call
                    if ( $this->is_ajax_request() )
                    {
                        $script = "<div id='subautosave' style='padding:2px;margin:3px;display:table'>Post Autosaved</div>
            		    <script>new Effect.Highlight('subautosave',{duration: 3.0});
            		            setTimeout(\"new Effect.Fade('subautosave')\",1000);                		            
            		            $('news_id').value=".$news->get('id').";
            		            </script>";
            		    $this->render(array('inline'=>$script));
            		    return;
                    }
	                
	                if ( isset($_POST['commit']) && $_POST['commit'] == 'Save and Continue Editing' )
	                {    	                
	                    $this->redirect_to(array('controller'=>'admin/news' ,'action'=>'modify?id='.$news->get('id')));     	                
     	            } elseif (!empty($_POST['go_back_to'])) {
     	                $this->redirect_to($_POST['go_back_to']);
	                } else {
	                    $this->redirect_to('index');   		               
	                }
	            } else {
	                flash('error','Post failed to save');
	            }

		    }
		    // get available custom fields
	        use_model('custom_fields');
	        $cf = new custom_fields();
	        $this->assign('custom_fields', $cf->assoc());
        }
        
        function delete()
        {
            if ( $this->is_post()  && has_access_to('News::Delete News')) {
		        $news = new News();
		        $id = (int) $_POST['id'];
		        if ( $news->load($id) )
		        {
		            $news->delete();
		            flash('notice','Post Deleted');
		        }
		    }
		    $this->redirect_to('index');
        }
        
        function categories()
        {
            // list all categories
            $news_categories = new News_Categories();
            $this->assign('report',$news_categories->get_paged_categories());
            $default_category = $news_categories->find_rows(
                                                        array(
                                                            'search'=>'first',
                                                            'conditions'=>'id=1',
                                                            'fields'=>'name'
                                                            )
                                                      );
            
            $this->assign('default_category',$default_category['name']);
        }
        
        function modify_category()
        {
            if(!has_access_to('News::Manage News Categories')) {
                $this->redirect_to('index');
                return;
            }
            $news_categories = new News_Categories();
            $this->assign_ref('category',$news_categories);
            $this->assign('all_categories',$news_categories->categories_as_list());
            if ( $this->is_get() && !empty($_GET['id']) )
            {
                $id = (int) $_GET['id'];
                $news_categories->load($id);
                $this->assign('cat',$news_categories->fields);
            }
            if ( $this->is_post() && !empty($_POST['category']) )
            {
                $id = $_POST['category']['id'];
                $news_categories->load($id);
                if ( $news_categories->update_fields($_POST['category']) )
                {
                    flash('notice','Category Saved');
                    $this->redirect_to('categories');
                } else {
                    $this->assign('cat',true);
                    flash('error','Category could not be saved');
                }
            }
        }        
        
        function add_category()
        {
            if(!has_access_to('News::Manage News Categories')) {
                $this->redirect_to('index');
                return;
            }
            if ( $this->s_post() && !empty($_POST['new_category']) )
            {
                $news_categories = new News_Categories();
                $news_categories->set('name',$_POST['new_category']);
                if ( $news_categories->save() )
                {
                    $this->assign('id',$news_categories->get('id'));
                    $this->assign('name',$news_categories->get('name'));
                    $this->render(array('partial'=>'_new_category.php'));
                } else {
                    $emsg    = "<script>alert('".escape_javascript(
                                                    strip_tags(
                                                        $news_categories->errors_to_string()
                                                              )
                                                 )."')</script>";
                    $this->render(array('inline'=>$emsg));
                }
            }
        }
        
        function delete_category()
        {
            if(!has_access_to('News::Manage News Categories')) {
                $this->redirect_to('index');
                return;
            }
            if ( $this->is_post() && isset($_POST['id']) )
            {
                $news_categories = new News_Categories();            
                if ( $news_categories->load( (int) $_POST['id']) )
                {
                    $news_categories->delete();
                    flash('notice','Category deleted');
                }
            }
            $this->redirect_to('categories');
        }
        
        function search()
        {
            if ( $this->is_post() )
            {
                // load the entry to edit by a title search
    		    if ( isset($_POST['action'])
    		        && $_POST['action'] == 'find_by_title' )
    		    {
    		        $news = new news();
    		        if (!$news->load('title=?',array($_POST['title'])))
    		        {
    		            flash('error','Post not found');
    		            $this->redirect_to('index');
    		            return;
    		        } else {
    		            $this->redirect_to('modify?id='.$news->get('id'));
    		            return;
    		        }
    	        }
                
                $news = new News();
    		    $found_news = $news->find_rows( array(
    		                                'conditions'=>array('lower(title) like ?', '%'.strtolower($_POST['title']).'%'),
    		                                'order' =>'title asc',
    		                                'limit'=>8,
    		                                'fields'=>'title'
    		                                ) );

    		    $this->assign('found_news',$found_news);
    		    $this->render(array('partial'=>'_found_news.php'));
            }
        }
        
    }

?>